import os
import json
from time import sleep

from rest_framework.decorators import action
from rest_framework.response import Response
from rest_framework.viewsets import GenericViewSet
from django.conf import settings

from .serializer import *
from util.requestOwn import my_request


class HistoryOnlineView(GenericViewSet):
    @action(detail=False, methods=["GET", ], url_path="fresh")
    def fresh_history(self, requests, *args, **kwargs):
        data = {}
        gateway_id = self.request.GET.get("gateway_id")
        is_connected = self.request.GET.get("is_connected")
        if is_connected == "True":
            is_connected = True
        else:
            is_connected = False
        data["gateway_id"] = int(gateway_id)
        data["is_connected"] = is_connected
        serializer = OnelineHistorySerializer(data=data)
        if serializer.is_valid():
            sleep(2)
            gateway_id =  serializer.create(data)
            if gateway_id:
                my_request.awake_gateway({"gateway_id": gateway_id})
            return Response({"code": 200, "msg": "OK"})
        raise ValidationError(20001)

